package com.service.impl;

import com.entity.CourseEntity;
import com.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.utils.PageUtils;
import com.utils.Query;


import com.dao.StoreupDao;
import com.entity.StoreupEntity;
import com.service.StoreupService;

@Service("storeupService")
public class StoreupServiceImpl extends ServiceImpl<StoreupDao, StoreupEntity> implements StoreupService {

	@Autowired
	private StoreupDao storeupDao;

	@Autowired
	private CourseService courseService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<StoreupEntity> page = this.selectPage(
                new Query<StoreupEntity>(params).getPage(),
                new EntityWrapper<StoreupEntity>()
        );
        return new PageUtils(page);
    }

	@Override
	public List<StoreupEntity> selectListEntity(Wrapper<StoreupEntity> wrapper) {
		return null;
	}

	@Override
	public StoreupEntity selectEntity(Wrapper<StoreupEntity> wrapper) {
		return null;
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params, Wrapper<StoreupEntity> wrapper) {
		  Page<StoreupEntity> page =new Query<StoreupEntity>(params).getPage();
	        page.setRecords(baseMapper.selectListEntity(page,wrapper));
	    	PageUtils pageUtil = new PageUtils(page);
	    	return pageUtil;
 	}

	@Override
	public StoreupEntity getStoreupByUserIdAndCourseId(Long userId, Long courseId) {
		if (userId == null || courseId == null) {
			return null;
		}
		StoreupEntity storeupEntity=storeupDao.getStoreupByUserIdAndCourseIdXml(userId, courseId);
		return storeupEntity;
	}
	@Override
	public PageUtils queryFavoriteCourses(Map<String, Object> params, Long userId) {
		EntityWrapper<StoreupEntity> ew = new EntityWrapper<>();
		ew.eq("user_id", userId);
		ew.eq("favorite", 1);

		Page<StoreupEntity> storeupPage = new Query<StoreupEntity>(params).getPage();
		storeupPage = this.selectPage(storeupPage, ew);

		List<StoreupEntity> storeupList = storeupPage.getRecords();

		if (storeupList.isEmpty()) {
			return new PageUtils(storeupPage);
		}

		Set<Long> courseIds = storeupList.stream()
				.map(StoreupEntity::getCourseId)
				.collect(Collectors.toSet());

		List<CourseEntity> courseList = courseService.selectBatchIds(courseIds);

		// 🔍 根据 title 进行模糊筛选
		String title = (String) params.get("title");
		if (title != null && !title.trim().isEmpty()) {
			String finalTitle = title.replace("%", "").toLowerCase();
			courseList = courseList.stream()
					.filter(course -> course.getTitle() != null &&
							course.getTitle().toLowerCase().contains(finalTitle))
					.collect(Collectors.toList());

			// 同步过滤收藏列表
			Set<Long> matchedCourseIds = courseList.stream()
					.map(CourseEntity::getId)
					.collect(Collectors.toSet());
			storeupList = storeupList.stream()
					.filter(s -> matchedCourseIds.contains(s.getCourseId()))
					.collect(Collectors.toList());
		}

		Map<Long, CourseEntity> courseMap = courseList.stream()
				.collect(Collectors.toMap(CourseEntity::getId, course -> course));

		// 构建新的返回对象列表，包含收藏信息和课程信息
		List<Map<String, Object>> resultList = new ArrayList<>();
		for (StoreupEntity storeup : storeupList) {
			Map<String, Object> item = new java.util.HashMap<>();
			// 添加 StoreupEntity 的所有字段
			item.put("id", storeup.getId());
			item.put("userId", storeup.getUserId());
			item.put("courseId", storeup.getCourseId());
			item.put("thumbsUp", storeup.getThumbsUp());
			item.put("thumbsDown", storeup.getThumbsDown());
			item.put("favorite", storeup.getFavorite());
			item.put("addTime", storeup.getAddTime());

			// 添加 CourseEntity 的字段
			CourseEntity course = courseMap.get(storeup.getCourseId());
			if (course != null) {
				item.put("courseTitle", course.getTitle()); // 课程标题
				item.put("coverImageUrl", course.getCoverImageUrl()); // 封面图片URL
				// 如果需要，可以添加更多课程字段
			} else {
				// 如果课程被删除了，可以设置默认值或者跳过
				item.put("courseTitle", "课程不存在");
				item.put("coverImageUrl", "");
			}
			resultList.add(item);
		}

		PageUtils pageUtils = new PageUtils(storeupPage); // 复制原始分页信息
		pageUtils.setList(resultList); // 设置新的数据列表

		return pageUtils;
	}
}
